import re
import subprocess
from pathlib import Path
from ffmpy import FFmpeg
from tinytag import TinyTag
import mutagen
import logging

logger = logging.getLogger(__name__)


def parse_cue_file(cue_file_path):
    """解析 CUE 文件，返回曲目的标题和对应的 INDEX 01 时间"""
    tracks = []
    current_track_title = None
    with open(cue_file_path, 'r', encoding='gbk') as cue_file:
        content = cue_file.readlines()
        for line in content:
            line = line.strip()
            title_match = re.match(r'TITLE "(.*)"', line)
            index_match = re.match(r'INDEX 01 (\d+:\d+:\d+(?:\.\d+)?)', line)  # 支持毫秒

            if title_match:
                current_track_title = title_match.group(1)
            elif index_match:
                current_index_time = index_match.group(1)
                # 取前 5 个字符，确保只保留 '00:00'
                if current_track_title:
                    current_index_time = current_index_time[:5]  # 仅保留前 5 个字符 'hh:mm'
                    tracks.append({"Title": current_track_title, "Index": current_index_time})
    print("解析得到的曲目信息:", tracks)
    return tracks

def get_wav_duration(source_file):
    """获取 WAV 文件的时长（秒）"""
    try:
        cmd = [
            'ffprobe', 
            '-v', 'error', 
            '-show_entries', 'format=duration', 
            '-of', 'default=noprint_wrappers=1:nokey=1',
            str(source_file)
        ]
        duration = subprocess.check_output(cmd).strip()
        return float(duration)  # 返回时长（秒）
    except Exception as e:
        print(f"获取 WAV 时长出错: {e}")
        return None

def check_file_exists(file):
    # 定义可能的后缀
    extensions = ['.wav', '.ape', '.flac', '.tta', '.tak']
    # 尝试所有可能的后缀
    for ext in extensions:
        file_path = file.with_suffix(ext)
        if file_path.exists():
            print(f"音频文件路径: {file_path}")
            return file_path
    
    print(f"找不到任何音频文件")
def split_wav(cue_file_path):
    """根据 tracks 列表分割 WAV 文件"""
    file = Path(cue_file_path)

    # 检查音频文件是否存在
    media_file = check_file_exists(file)
    media_file_path = Path(media_file)
    
    # 获取 WAV 文件时长
    wav_duration = get_wav_duration(media_file_path)  # 解析出文件路径
    if wav_duration is None:
        return
        
    # 解析 CUE 文件
    tracks = parse_cue_file(file)  

    # 定义输出目录
    output_directory = file.parent
    output_directory.mkdir(parents=True, exist_ok=True)  # 确保输出目录存在
    try:
        
        for index, track in enumerate(tracks):
            start_time = track['Index']
            # 确定结束时间
            if index < len(tracks) - 1:
                end_time = tracks[index + 1]['Index']
            else:
                end_time = wav_duration  # 使用 WAV 时长作为结束时间

            # 生成输出文件名{index + 1:02}，其中 02 表示数字至少占用两位，如果位数不足则在前面补零
            target_file = output_directory / f"{index + 1:02}.{track['Title']}{media_file_path.suffix}"  
            
            # 执行 FFmpeg 来分割音频文件
            ff = FFmpeg(
                inputs={str(media_file_path): f'-ss {start_time} -to {end_time}'},  # 仅传入输入文件
                outputs={str(target_file): f'-vn -acodec copy -y'}  # 在输出中指定参数
            )
            print(f"正在分割: {track['Title']} 从 {start_time} 到 {end_time}")
            ff.run()

            print(f'已导出: {target_file}')
    except Exception as e:
        logger.error(f"转换{track['Title']}时出错: {e}")


if __name__ == "__main__":
    cue_file_path = r"E:\ER\ss\陈慧娴《经典重逢DSD》\CDImage.cue"  # CUE 文件路径
    split_wav(cue_file_path)
